package com.esfak47.mediafetcher.plugins.javafxapp;

import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

import java.util.function.Consumer;

import static com.esfak47.mediafetcher.core.constants.Constants.SEVER_PORT;

public class WebViewApplication extends Application {
    private static Consumer<Void> onEnd;
    private Scene scene;
    public static void main(String[] args) {
        launch(WebViewApplication.class,args);
    }

    public static void setOnEnd(Consumer<Void> onEnd) {
        WebViewApplication.onEnd = onEnd;
    }

    @Override
    public void start(Stage stage) {
        // create the scene
        stage.setTitle("视屏抓取服务");
        scene = new Scene(new Browser(), 1333, 768, Color.web("#666970"));
        stage.setScene(scene);
        //scene.getStylesheets().add("webviewsample/BrowserToolbar.css");
        stage.show();
        stage.setOnCloseRequest(event -> {
            if (onEnd != null) {
                onEnd.accept(null);
            }
        });
    }


}

class Browser extends Region {

    final WebView browser = new WebView();
    final WebEngine webEngine = browser.getEngine();

    public Browser() {
        //apply the styles
        getStyleClass().add("browser");
        // load the web page
        webEngine.load("http://localhost:"+SEVER_PORT);
        //add the web view to the scene
        getChildren().add(browser);

    }

    private Node createSpacer() {
        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);
        return spacer;
    }

    @Override
    protected void layoutChildren() {
        double w = getWidth();
        double h = getHeight();
        layoutInArea(browser, 0, 0, w, h, 0, HPos.CENTER, VPos.CENTER);
    }

    @Override
    protected double computePrefWidth(double height) {
        return 750;
    }

    @Override
    protected double computePrefHeight(double width) {
        return 500;
    }
}